package indi.cyh.fastservice.tool;

import indi.cyh.fastservice.base.entity.http.ResponseBase;
import org.springframework.stereotype.Component;


@Component
public class RestResultTool {

    final static String SUCCESS_MESSAGE = "调用成功！";
    final static String FAILED_MESSAGE = "调用失败！";
    final static String EXCEPTION_MESSAGE = "调用异常！";


    /**
     * 消息处理(接口正常结束)
     *
     * @param res 执行结果
     * @return antu.microservice.ResponseBase
     * @author CYH
     * @date 2021/1/4 0004 15:33
     **/
    public ResponseBase getOverResult(Object res) {
        ResponseBase response = new ResponseBase();
        String resTypeName = res.getClass().getName();
        boolean isSuccess = false;
        if ("boolean".equals(resTypeName)) {
            isSuccess = Boolean.parseBoolean(res.toString());
        }
        response.setResult(res);
        if (isSuccess) {
            response.setMessage(SUCCESS_MESSAGE);
            response.setStatus(ResponseBase.ok);
        } else {
            response.setMessage(FAILED_MESSAGE);
            response.setStatus(ResponseBase.failed);
        }
        return response;
    }

    /**
     * 消息处理(接口正常结束)
     *
     * @param res 执行结果
     * @return antu.microservice.ResponseBase
     * @author CYH
     * @date 2021/1/4 0004 15:33
     **/
    public ResponseBase getOverResult(Object res, String errorMessage, String successMessage) {
        ResponseBase response = new ResponseBase();
        String resTypeName = res.getClass().getName();
        boolean isSuccess = true;
        if ("boolean".equals(resTypeName)) {
            isSuccess = Boolean.parseBoolean(res.toString());
        }
        response.setResult(res);
        if (isSuccess) {
            response.setMessage(successMessage);
            response.setStatus(ResponseBase.ok);
        } else {
            response.setMessage(errorMessage);
            response.setStatus(ResponseBase.failed);
        }
        return response;
    }


    /**
     * 消息处理(接口异常结束)
     *
     * @param e 捕获到的异常
     * @return antu.microservice.ResponseBase
     * @author CYH
     * @date 2021/1/4 0004 15:34
     **/
    public ResponseBase getExceptionResult(String token, String DBLog, Exception e) {
        ResponseBase response = new ResponseBase();
        response.setResult(e.getMessage());
        response.setMessage(EXCEPTION_MESSAGE);
        response.setStatus(ResponseBase.failed);
        e.printStackTrace();
        return response;
    }
}